package com.sx.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DatabaseUtil {
    // 创建一个Druid数据源对象
    private static DruidDataSource dataSource;
    private static Logger log = LogManager.getLogger(DatabaseUtil.class);

    static {
        // 加载配置文件
        Properties properties = new Properties();
        try {
            properties.load(DatabaseUtil.class.getClassLoader().getResourceAsStream("mysql.properties"));
            // 通过配置文件创建数据源
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("获取数据库连接失败");
        }
    }

    /**
     * 获取数据库连接的方法
     *
     * @return 返回一个数据库连接对象，如果获取失败返回null
     */
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            // e.printStackTrace();
            log.error("获取数据库连接失败");
            return null;
        }
    }
}